﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Reflection;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class PropChangedActionWrapper : AroundMethodBase, IAroundInvoke
	{
		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			if (when != CutpointType.Before || !context.TargetMethod.Name.Contains("set_"))
				return;

			object thisObject = context.Target;
			string propInfoName = context.TargetMethod.Name.Substring(4);
			Type t = thisObject.GetType();
			PropInfo propInfo = t.GetPropInfo(propInfoName);
			PropertyChangedActionAttribute[] attrs = propInfo.GetAttributes<PropertyChangedActionAttribute>();

			if (attrs != null && attrs.Length > 0)
			{
				object oldValue = propInfo.GetValue(thisObject);
				object newValue = context.Arguments[0];

				for (int n = 0; n < attrs.Length; n++)
				{
					PropertyChangedActionAttribute attr = attrs[n];
					MethodInfo method = attr.GetMethod(t);

					if (method != null)
						method.Invoke(thisObject, new object[] { context, propInfo, oldValue, newValue });
					else
						attr.SetOnForeignClass(t, thisObject, newValue);
				}
			}
		}
	}
}

